﻿using CMS.DataAccess;
using CMS.Excep;
using CMS.Model;

namespace CMS.AOP
{
    public class ScheduleConflictSaveAction : IBeforeSaveOrDelAction<ScheduleModel>
    {
        public void DoAction(ScheduleModel? _old, ScheduleModel? _new)
        {
            if (_new == null) return;
            CheckClassDuplicate(_new);
            CheckTeacherDuplicate(_new);
        }
        private void CheckClassDuplicate(ScheduleModel _new)
        {
            DbQuery<ScheduleModel> qry = new DbQuery<ScheduleModel>();
            DbQuery<DseClassModel> clsQry = new DbQuery<DseClassModel>();
            DbQuery<CourseModel> courseQry = new DbQuery<CourseModel>();
            var cond = CondCollection.True().Eq(nameof(ScheduleModel.DseClass), _new.DseClass)
                .Eq(nameof(ScheduleModel.Date), _new.Date)
                .Eq(nameof(ScheduleModel.Seq), _new.Seq)
                .NoEq(nameof(ScheduleModel.Pk), _new.Pk);


            var exist = qry.Where(cond).First();
            if (exist != null)
            {
                if (!(exist.Optional == "Y" && _new.Optional == "Y"))
                {
                    var c = clsQry.Get(exist.DseClass);
                    var u = courseQry.Get(exist.Course);
                    throw new MyOptException($"{c.ClassName}[{_new.Date}]第{_new.Seq}节课已经安排了非选修{u.CourseName}");
                }
            }
        }
        private void CheckTeacherDuplicate(ScheduleModel _new)
        {
            DbQuery<ScheduleModel> qry = new DbQuery<ScheduleModel>();
            DbQuery<DseClassModel> clsQry = new DbQuery<DseClassModel>();
            DbQuery<UserModel> usrQry = new DbQuery<UserModel>();
            var cond = CondCollection.True().Eq(nameof(ScheduleModel.Teacher), _new.Teacher)
                .Eq(nameof(ScheduleModel.Date), _new.Date)
                .Eq(nameof(ScheduleModel.Seq), _new.Seq)
                .NoEq(nameof(ScheduleModel.Pk), _new.Pk);
            var exist = qry.Where(cond).First();
            if (exist != null)
            {
                if (exist.GroupClass != "Y" )
                {
                    var c = clsQry.Get(exist.DseClass);
                    var u = usrQry.Get(_new.Teacher);
                    throw new MyOptException($"{u.UserName}[{_new.Date}]第{_new.Seq}节课已经安排了班级[{c.ClassName}]非大课");
                }
            }
        }
    }
}
